<template>
  <div class="main_content" ref="tbDatalog">
    <el-table
      :data="roles"
      border
      :fit="true"
      class="flex-table"
      :max-height="tbDatalogHeight"
      :header-cell-style="{ 'font-weight': 'bold', color: '#2A2A2A' }"
    >
      <el-table-column prop="type" label="角色类型" width="180">
        <template slot-scope="scope">
          <span>{{ getRoleTypeName(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="(permission, index) in flattenPermissions(scope.row.data)"
            :key="index"
            type="success"
            closable
            @close="removePermission(scope.$index, permission)"
          >
            {{ permission.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="openDialog(scope.row)">
            {{
              flattenPermissions(scope.row.data).length > 0 ? "修改" : "添加"
            }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 模态框 -->
    <el-dialog
      title="权限配置"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        node-key="value"
        :props="defaultProps"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="savePermissions">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PermissionConfig",
  tbDatalogHeight: 500,
  props: {
    qtCall: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      roles: [],
      dialogVisible: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      selectedRole: null,
      query: {
        type: 0,
        data: [],
      },
    };
  },
  mounted() {
    if (process.env.NODE_ENV === "production") {
      this.getAllRoleData();
      setTimeout(() => {
        this.getAllPermissionData();
      }, 300);
    } else {
      this.getAllRoleData();
      this.getAllPermissionData();
    }

    this.$nextTick(() => {
      this.tbDatalogHeight = this.getTbHeight();
    });
  },
  methods: {
    getTbHeight() {
      var ret = this.$refs.tbDatalog.offsetHeight;
      return ret;
    },
    getRoleTypeName(type) {
      const typeMapping = {
        1: "操作员",
        2: "技术员",
        3: "管理员",
        99: "超级管理员",
      };
      return typeMapping[type] || "未知角色";
    },
    flattenPermissions(data) {
      const permissions = [];

      const traverse = (nodes, parentLabel = "") => {
        nodes.forEach((node) => {
          const currentLabel = parentLabel
            ? `${parentLabel} - ${node.label}`
            : node.label;
          if (node.children) {
            traverse(node.children, currentLabel);
          } else {
            permissions.push({ label: currentLabel, value: node.value });
          }
        });
      };
      if (data.length !== 0) {
        traverse(data);
      }
      return permissions;
    },
    getAllRoleData() {
      if (process.env.NODE_ENV === "production") {
        console.log("NeedRefreshAllUserLimits");
        this.qtCall.JsToQt("NeedRefreshAllUserLimits", {});
        this.qtCall.QtToJs.connect((func, json) => {
          if (func === "RefreshAllUserLimits") {
            const datas = JSON.parse(json);
            if (datas.code === 200) {
              this.roles = JSON.parse(datas.data["UserLimits"]);
            }
          }
        });
      } else {
        this.roles = [
          {
            type: "1",
            data: [],
          },
          {
            type: "2",
            data: [
              {
                label: "设备管理",
                value: "equipmentManagement",
                children: [
                  {
                    label: "设备维护",
                    value: "equipmentManagement.equipmentMaintenance",
                  },
                ],
              },
              {
                label: "用户配置",
                value: "userConfiguration",
                children: [
                  {
                    label: "权限配置",
                    value: "productionManagement.permissionConfiguration",
                  },
                ],
              },
            ],
          },
          {
            type: "3",
            data: [
              {
                label: "设备管理",
                value: "equipmentManagement",
                children: [
                  {
                    label: "设备运行状态",
                    value: "equipmentManagement.equipmentOperationStatus",
                  },
                  {
                    label: "设备日志",
                    value: "equipmentManagement.equipmentLog",
                  },
                  {
                    label: "设备维护",
                    value: "equipmentManagement.equipmentMaintenance",
                  },
                  {
                    label: "点检记录",
                    value: "equipmentManagement.inspectionRecord",
                  },
                  {
                    label: "点检内容",
                    value: "equipmentManagement.inspectionContent",
                  },
                  {
                    label: "元件寿命统计",
                    value: "equipmentManagement.componentLifeStatistics",
                  },
                  {
                    label: "保养计划",
                    value: "equipmentManagement.maintenancePlan",
                  },
                  {
                    label: "设备信息",
                    value: "equipmentManagement.equipmentInformation",
                  },
                ],
              },
              {
                label: "用户配置",
                value: "userConfiguration",
                children: [
                  {
                    label: "用户管理",
                    value: "productionManagement.userManagement",
                  },
                  {
                    label: "权限配置",
                    value: "productionManagement.permissionConfiguration",
                  },
                  {
                    label: "参数配置",
                    value: "productionManagement.parameterConfiguration",
                  },
                ],
              },
            ],
          },
          {
            type: "99",
            data: [],
          },
        ];
      }
    },
    getAllPermissionData() {
      if (process.env.NODE_ENV === "production") {
        console.log("NeedQueryBaseUserLimits");
        this.qtCall.JsToQt("NeedQueryBaseUserLimits", {});
        this.qtCall.QtToJs.connect((func, json) => {
          if (func === "QueryBaseUserLimits") {
            const datas = JSON.parse(json);
            if (datas.code === 200) {
              this.treeData = datas.data["BaseUserLimits"];
            }
          }
        });
      } else {
        const baseUserLimitsValue =
          '[\n    {\n        "children": [\n            {\n                "label": "实时数据",\n                "value": "productionData.realTimeData"\n            },\n            {\n                "label": "历史数据",\n                "value": "productionData.historyData"\n            }\n        ],\n        "label": "生产数据",\n        "value": "productionData"\n    },\n    {\n        "children": [\n            {\n                "label": "首页",\n                "value": "qualityAnalysis.home"\n            },\n            {\n                "label": "缺陷类别",\n                "value": "qualityAnalysis.defectCategory"\n            },\n            {\n                "label": "缺陷位置",\n                "value": "qualityAnalysis.defectPosition"\n            },\n            {\n                "label": "缺陷分析",\n                "value": "qualityAnalysis.defectAnalysis"\n            },\n            {\n                "label": "质量预警",\n                "value": "qualityAnalysis.qualityWarning"\n            }\n        ],\n        "label": "质量分析",\n        "value": "qualityAnalysis"\n    },\n    {\n        "children": [\n            {\n                "label": "设备运行状态",\n                "value": "equipmentManagement.equipmentOperationStatus"\n            },\n            {\n                "label": "设备日志",\n                "value": "equipmentManagement.equipmentLog"\n            },\n            {\n                "label": "设备维护",\n                "value": "equipmentManagement.equipmentMaintenance"\n            },\n            {\n                "label": "点检记录",\n                "value": "equipmentManagement.inspectionRecord"\n            },\n            {\n                "label": "点检内容",\n                "value": "equipmentManagement.inspectionContent"\n            },\n            {\n                "label": "元件寿命统计",\n                "value": "equipmentManagement.componentLifeStatistics"\n            },\n            {\n                "label": "保养计划",\n                "value": "equipmentManagement.maintenancePlan"\n            },\n            {\n                "label": "设备信息",\n                "value": "equipmentManagement.equipmentInformation"\n            }\n        ],\n        "label": "设备管理",\n        "value": "equipmentManagement"\n    },\n    {\n        "children": [\n            {\n                "label": "用户管理",\n                "value": "userConfiguration.userManagement"\n            },\n            {\n                "label": "权限配置",\n                "value": "userConfiguration.permissionConfiguration"\n            },\n            {\n                "label": "参数配置",\n                "value": "userConfiguration.parameterConfiguration"\n            }\n        ],\n        "label": "用户配置",\n        "value": "userConfiguration"\n    }\n]\n';
        this.treeData = JSON.parse(baseUserLimitsValue);
        console.log('treedata', this.treeData)
      }
    },
    openDialog(role) {
      this.selectedRole = role;
      this.dialogVisible = true;
      this.$nextTick(() => {
        const selectedKeys = this.flattenPermissions(role.data).map(
          (permission) => permission.value
        );
        this.$refs.tree.setCheckedKeys(selectedKeys);
      });
    },
    closeDialog() {
      this.dialogVisible = false;
      this.selectedRole = null;
    },
    removePermission(roleIndex, permission) {
      const roleData = this.roles[roleIndex].data;
      // 遍历 roleData 并过滤掉匹配的子节点
      roleData.forEach((item, index) => {
        if (item.children) {
          item.children = item.children.filter(
            (child) => child.value !== permission.value
          );

          // 如果 children 数组为空，移除当前节点
          if (item.children.length === 0) {
            roleData.splice(index, 1);
          }
        }
      });
      // 更新 roles 数组
      this.roles[roleIndex].data = roleData;
      console.log(roleData, "Updated Roles");

      this.query.type = this.roles[roleIndex].type;
      this.query.data = roleData;
      this.updatePermissions();
    },
    savePermissions() {
      if (this.selectedRole) {
        // 确保 selectedPermissions 是一个数组
        const selectedPermissions = Array.isArray(this.selectedPermissions)
          ? this.selectedPermissions
          : [];

        // 获取选中节点的 keys
        const checkedKeys = this.$refs.tree.getCheckedKeys();

        // 遍历 treeData，匹配选中的 permissions，并构造嵌套结构
        const buildPermissionData = (nodes) => {
          return nodes
            .map((node) => {
              // 检查节点本身是否被选中
              const isChecked = checkedKeys.includes(node.value);

              // 递归检查子节点是否被选中
              const matchingChildren = node.children
                ? buildPermissionData(node.children)
                : [];

              // 如果节点本身或其子节点被选中，保留该节点
              if (isChecked || matchingChildren.length > 0) {
                const result = {
                  label: node.label,
                  value: node.value,
                };

                // 仅当有子节点时才添加 children 字段
                if (matchingChildren.length > 0) {
                  result.children = matchingChildren;
                }
                return result;
              }
              return null;
            })
            .filter((item) => item !== null); // 过滤掉未选中的节点
        };
        const nestedPermissions = buildPermissionData(this.treeData);
        this.selectedRole.data = nestedPermissions;
        // 打印选中的结果
        console.log("nestedPermissions: ", nestedPermissions);
        console.log(this.selectedRole, "Selected Role with Permissions");
        this.query.type = this.selectedRole.type;
        this.query.data = nestedPermissions;
        this.updatePermissions();
      }
      this.dialogVisible = false;
    },
    updatePermissions() {
      // 更新权限配置
      if (process.env.NODE_ENV === "production" && this.query.type !== 0) {
        console.log("NeedUpdateUserLimit query: ", this.query);
        this.qtCall.JsToQt("NeedUpdateUserLimit", this.query);
        // this.qtCall.QtToJs.connect((func, json) => {
        //   if (func === "UpdateUserLimit") {
        //     const datas = JSON.parse(json);
        //     if (datas.code === 200) {
        //       this.$message.success('权限配置成功');
        //       this.query = {
        //         type: 0,
        //         data: [],
        //       };
        //       this.getAllRoleData();
        //     } else {
        //       this.$message.error('权限配置失败');
        //     }
        //   }
        // });
        this.$message.success("权限配置成功");
        this.query = {
          type: 0,
          data: [],
        };
      } else {
        this.$message.success("权限配置成功");
        this.query = {
          type: 0,
          data: [],
        };
      }
    },
  },
};
</script>

<style scoped>
.main_content {
  display: flex;
  flex-direction: column;
  height: 80vh;
}
</style>
